<template>
  <!-- 产品授权 -->
  <div>
    <FormPanel
      ref="FormPanel"
      :list="initForm"
      :cols="1"
      :formType="formType"
      :labelWidth="160"
      :isSubmitBtn="false"
      @formChange="formChangeHandle"
      class="mtop"
    />
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import autoLoding from '@/utils/loding'; //等待框

import { getSeries, getModel, findFinanceCompanySeriesList } from '@/api/cms-common/basedata';

import { findFinanceCompany } from '@/api/cms-api/origin/originInfo/OEM';

export default {
  mixins: [dictionary, autoLoding],
  model: {
    prop: 'pdata',
    event: 'click'
  },
  props: {
    pdata: {
      type: Object,
      default: () => ({})
    },
    formType: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      initForm: this.initFormFun(),
      brandId: 1
    };
  }, //brandId：品牌@1//seriesId：车系@2//modelId：车型@3
  mounted() {
    this.createAuthList({});
  },
  methods: {
    //初始化数据(回显)
    init() {
      this.initForm.forEach(x => {
        if (this.pdata[x.fieldName]) {
          x.initialValue = this.pdata[x.fieldName];
        }
      });
      //取第一个的值
      let financeCompanyIds = this.initForm.find(item => item.fieldName === 'dealerAttachAuthList').initialValue;
      // let seriesIds = this.initForm.find(item => item.fieldName === 'dealerAttachSeriesList').initialValue;
      this.getSeriesFn({ financeCompanyIds: financeCompanyIds.join(',') });
      // getModelFn
      // this.seriesChange(seriesIds, false);
    },
    //
    async createAuthList(params) {
      let res = await findFinanceCompany(params);
      if (res.resultCode === 200) {
        this.initForm.find(item => item.fieldName === 'dealerAttachAuthList').itemList = [];
        res.data.forEach(x => {
          this.initForm.find(item => item.fieldName === 'dealerAttachAuthList').itemList.push({ text: x.financeCompanyName, value: x.financeCompanyId });
        });
      }
    },
    //获取车系（）
    async getSeriesFn(params) {
      if (!params) {
        return;
      }
      let dealerAttachSeriesList = this.initForm.find(item => item.fieldName === 'dealerAttachSeriesList').initialValue;
      // let loadingVm = this.openLoding('.cover-container');
      this.initForm.find(item => item.fieldName === 'dealerAttachSeriesList').itemList = [];
      this.initForm.find(item => item.fieldName === 'dealerAttachSeriesList').initialValue = [];

      let res = await findFinanceCompanySeriesList(params);
      if (res.resultCode === 200) {
        res.data.forEach(x => {
          this.initForm.find(item => item.fieldName === 'dealerAttachSeriesList').itemList.push({ text: x.seriesName, value: x.seriesId });
          dealerAttachSeriesList.forEach(v=>{
            if(x.seriesId==v){
              this.initForm.find(item => item.fieldName === 'dealerAttachSeriesList').initialValue.push(v);
            }
          });
       });
             this.seriesChange(this.initForm.find(item => item.fieldName === 'dealerAttachSeriesList').initialValue, false);
      }
      // this.closeLoding(loadingVm);
    },
    //获取车型（mini）
    async getModelMini(params, selectionList, isInit) {
      let res = await getModel(params);
      if (res.resultCode === 200) {
        res.data.forEach(x => {
          this.initForm.find(item => item.fieldName === 'dealerAttachModelList').itemList.push({ text: x.modelName, value: x.modelId });
          //禁止初始化
          if (isInit) {
            selectionList.push(x.modelId);
          }
        });
      }
    },
    async authChange(authId) {
      this.$nextTick(() => {
        this.$refs.FormPanel.$refs.form.clearValidate();
      });
      if (Array.isArray(authId) && authId.length != 0) {
        this.getSeriesFn({ financeCompanyIds: authId.join(',') });
      }
    },
    //车系变更后，查询车型
    async seriesChange(props, isInit) {
      let getProtocalNum = new Set(props);
      props = Array.from(getProtocalNum);
      //禁止选择
      // this.initForm[1].disabled = true;
      // let loadingVm = this.openLoding('.cover-container');
      this.initForm.find(item => item.fieldName === 'dealerAttachModelList').itemList = [];
      let selectionList = [];
      // debugger
      for (let i = 0; props.length >= i; i++) {
        let res = await this.getModelMini({ brandId: this.brandId, seriesId: props[i] }, selectionList, isInit);
      }
      //禁止初始化
      if (isInit) {
        //全都选上
        this.initForm.find(item => item.fieldName === 'dealerAttachModelList').initialValue = selectionList;
      }
      //取消禁止选择
      // this.initForm[1].disabled = false;
      // this.closeLoding(loadingVm);
    },
    formChangeHandle(val) {
      this.pdata = Object.assign(this.pdata, val);
      //传递数据到父组件里
      this.$emit('click', this.pdata);
      //触发外部的事件，以标志着本表单已经准备完毕
      // this.$emit('formchange', this.pdata);
    },
    async saveDialog() {
      let flag = true;
      let err = this.$refs.FormPanel.SUBMIT_FORM();
      await this.$refs.FormPanel.$refs.form.validate().then(res => {
        console.log("res1:", res);
      }).catch(err => {
        console.log("err1:", err);
        flag = false;
      });
      console.log("flag:", flag);
      return flag;
      // this.$notify.warning({title: '提示信息',message:'只能选择一条记录'});
    },
    //搜索数据
    initFormFun() {
      return [
        {
          type: 'MULTIPLE_CHECKBOX',
          label: '经销商形式',
          fieldName: 'dealerAttachAuthList',
          initialValue: [],
          // itemList: this.createDictList('2555'), //复选框数据源
          itemList: [], //复选框数据源
          change: props => this.authChange(props),
          // rules: [
          //   {
          //     required: true,
          //     message: '必填',
          //     trigger: 'blur'
          //   }
          // ]
        },
        {
          type: 'MULTIPLE_CHECKBOX',
          label: '车系',
          fieldName: 'dealerAttachSeriesList',
          initialValue: [],
          disabled: false,
          // itemList: this.seriesList, //复选框数据源
          itemList: [],
          change: props => this.seriesChange(props, true),
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'blur'
            }
          ]
        },
        {
          type: 'MULTIPLE_CHECKBOX',
          label: '车型',
          fieldName: 'dealerAttachModelList',
          initialValue: [],
          itemList: [], //复选框数据源
          rules: [
            {
              required: true,
              message: '必填',
              trigger: 'blur'
            }
          ]
        }
      ];
    }
  }
};
</script>
